package com.huellas.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.huellas.bean.CitaBean;
import com.huellas.excepcion.DAOExcepcion;
import com.huellas.util.ConexionBD;

public class CitaDAO extends BaseDAO{

	//Metodo para insertar registro de cita de tarea
	public void insertarCita(CitaBean citaBean) throws DAOExcepcion {
		String query = "insert into Cita(CoCita,FeCita,FeHora,FlTipoCita,CoEstadoCita,CoPaciente, CoDoctor) values (?,?,?,?,?,?,?)";
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			connection = ConexionBD.obtenerConexion();
			preparedStatement = connection.prepareStatement(query);
			preparedStatement.setInt(1, citaBean.getCoCita());
			preparedStatement.setString(2, citaBean.getFeCita());
			preparedStatement.setString(3, citaBean.getFeHora());
			preparedStatement.setString(4, citaBean.getFlTipoCita());
			preparedStatement.setInt(5, citaBean.getEstadoCitaBean().getCoEstadoCita());
			preparedStatement.setInt(6, citaBean.getPacienteBean().getCoPaciente());
			preparedStatement.setInt(7, citaBean.getUsuarioBean().getCoUsuario());
			
			int i = preparedStatement.executeUpdate();
			
			if (i != 1) {
				throw new SQLException("No se pudo insertar");
			}
			// Obtener el ultimo id
			int id = 0;
			query = "select last_insert_id()";
			preparedStatement = connection.prepareStatement(query);
			resultSet = preparedStatement.executeQuery();
			
			if (resultSet.next()) {
				id = resultSet.getInt(1);
			}
			citaBean.setCoCita(id);

		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(resultSet);
			this.cerrarStatement(preparedStatement);
			this.cerrarConexion(connection);
		}
	}
}
